package cn.erp.app.alert.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.erp.app.service.BaseInfoService;
import cn.erp.app.util.EuiRender;
import cn.erp.common.model.SvcBaseinfo;
import cn.erp.common.model.SvcRecord;

import com.jfinal.common.controller.BaseController;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Table;
import com.jfinal.plugin.activerecord.TableMapping;
@ControllerBind(controllerKey="/home",viewPath="/home")
public class AlertController extends BaseController{
	public void index() {
		List<SvcBaseinfo> baseInfo = BaseInfoService.me.getAllMateriel();
		setAttr("materiel", baseInfo);
		render("alert_index.html");
	}
	
	public void getdata () {
		int pageNumber = getParaToInt("page", 1);
		int pageSize = getParaToInt("rows", 10);
		SvcRecord svc = getModel(SvcRecord.class, "alert");

		Table table = TableMapping.me().getTable(SvcRecord.class);

		String sql = "select * ,DATE_FORMAT(NOW(),'%Y-%m-%d') as currentDate ";
		String from = " from (select c.*, (case when c.categoryId='001' then p.alertNum else s.alertNum end) alertnum,(case when c.categoryId='001' then p.alertTime else s.alertTime end) alerttime from (select r.*,((case when sum(r1.num) is null then 0 else sum(r1.num) end)-(case when sum(r2.num) is null then 0 else sum(r2.num) end)) as count	from svc_record r "+ 
"left join svc_record r1 on r1.m_p_id = r.m_p_id and r1.id = r.id and r1.flag='001' or r1.flag='003' "+ 
"left join svc_record r2 on r2.m_p_id = r.m_p_id and r1.id = r.id  and r2.flag='002' group by r.m_p_id,r.categoryId) c "+ 
"left join svc_produce_category p on  c.categoryId='001' and p.id=c.m_p_id "+ 
"left join svc_materiel_subdivision s  on (c.categoryId='002' or c.categoryId='003') and  s.id = c.m_p_id "+  
"where (p.alertNum>c.count or s.alertNum>c.count) or ((c.proDate is not null and (datediff(DATE_FORMAT(NOW(), '%y-%m-%d'),c.proDate)>p.alertTime or datediff(DATE_FORMAT(NOW(), '%y-%m-%d'),c.proDate)>s.alertTime)))) o where 1=1";

		List<Object> args = new ArrayList<Object>();
		Map<String, Class<?>> columnmap = table.getColumnTypeMap();

		for (Map.Entry<String, Class<?>> entry : columnmap.entrySet()) {
			String cname = entry.getKey();
			Class<?> type = entry.getValue();
			Object val = svc.get(cname);
			if (val != null) {
				if (type == String.class) {// 字符串
					from += " and  o." + cname + " like  ? ";
					args.add("%" + val + "%");
				} else {
					from += " and  o." + cname + " =  ? ";
					args.add(val);
				}
			}
		}

		Page<SvcRecord> result = SvcRecord.dao.paginate(pageNumber, pageSize, sql, from, args.toArray());

		render(EuiRender.page(result));
	}
}
